package cn.candy.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    //在处理器执行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("token");
        if(token != null){
            Object obj = redisTemplate.opsForValue().get(token);
            if(obj != null){//登录了 ，并且没有过期
                //刷新登录过期时间
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                //放行
                return true;
            }
        }
        //跳转登录页面
        response.setCharacterEncoding("UTF-8");
        //告诉浏览器我要给你响应一个json数据，用Utf-8编码
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
